var score=0
var timer=null
var nub=1000
$(function (){
    // carMove()
    makeCar()
})
/*function carMove(){

    var code=2
    document.onkeydown=function(even){
        $("audio")[1].play()
        // alert(even.keyCode)
        if(even.keyCode==37){
         code--
         if(code<0){
            code=0
         }
        }
        if (even.keyCode == 39){
            code++
            if(code>4){
                code=4
            }
        }
        $("#heroCa").animate({
            "left":code*20+2+"%"
        },80)
    }
}*/
function addenemy(){
    var enemy=document.createElement("div")
    enemy.className="enemyCar"
    var code=Math.floor(Math.random()*5)

    enemy.style.left=code*20+2+"%"
    //设计图片编号
    var imgcode=Math.floor(Math.random()*12+1)


    enemy.style.backgroundImage = "url(img/bottom4" + imgcode + ".png)"

   
    $(".gamebox")[0].appendChild(enemy)

    var speed = Math.floor(Math.random() * 2000 + 1500)
    console.log(speednub)

    $(enemy).animate({"top":"100%"},1500,function(){
        score++
        $("#score").html("得分："+score)

        $(this).remove()
    })
    ko(enemy)
}

function makeCar(){
   timer= setInterval(function(){
        addenemy()
    },nub)
}

function ko (enemy){
    var heroCar=document.getElementById("#heroCar")

    var hero_w=heroCar.offsetWidth
    var hero_h=heroCar.offsetHeight

    setInterval(function(){
        var hero_top=heroCar.offsetTop
        var hero_left=heroCar.offsetLeft
        
        var enemy_top=enemy.offsetTop
        var enemy_left=enemy.offsetLeft

        if(Math.abs(hero_top-hero_top)<hero_h&&Math.abs(enemy_left-hero_left)<hero_w){
          gameover()
        }   
    },10)
}

function gameover(){
    $("#heroCar").animate({
        "top":"100%"
    },200)
    clearInterval(timer)
      nub=300
     makeCar()
     $("#gameover").fadeIn(500)
     $("#score").fadeIn(500)
     restart()
}
function restart(){
    document.onkeydown=function(e){
        if(e.keyCode==13){
        document.location.reload()
        }
    }
}